package com.imonsoft.sqm.service.business.supplier_quality;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import com.google.gson.reflect.TypeToken;
import com.imonsoft.common.constant.ConstantDict;
import com.imonsoft.common.constant.ConstantSqm;
import com.imonsoft.common.exception.SystemException;
import com.imonsoft.common.httpModel.DataGrid;
import com.imonsoft.common.httpModel.Pager;
import com.imonsoft.common.httpModel.ReturnMessage;
import com.imonsoft.common.util.DateUtil;
import com.imonsoft.common.util.JsonUtil;
import com.imonsoft.common.util.SendMail;
import com.imonsoft.common.util.StringUtil;
import com.imonsoft.sqm.dao.business.supplier_quality.QualitySystemDAO;
import com.imonsoft.sqm.pojo.basedata.Supplier;
import com.imonsoft.sqm.pojo.business.supplier_quality.QualitySystem;
import com.imonsoft.sqm.pojo.business.supplier_quality.QualitySystemExample;
import com.imonsoft.sqm.pojo.sys.User;
import com.imonsoft.sqm.service.basedata.DictionaryService;
import com.imonsoft.sqm.service.basedata.SupplierService;
import com.imonsoft.sqm.service.excel.QuanlitySystemExcel.QuanlitySystemExcelService;
import com.imonsoft.sqm.validator.business.supplier_quality.QualitySystemValidator;
import com.imonsoft.sqm.vo.business.supplier_quality.QualitySystemVo;

@Service("qualitySystemService")
public class QualitySystemServiceImpl implements QualitySystemService {
	@Autowired
	private QualitySystemDAO qualitySystemDAO;
	@Autowired
	private SupplierService supplierService;
	@Autowired
	private QualitySystemValidator qualitySystemValidator;
	@Autowired
	private QuanlitySystemExcelService quanlitySystemExcelService;
	@Autowired 
	private DictionaryService dictionaryService;
	@Override
	public int delete(Long id) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public List<QualitySystem> findList(QualitySystem entity) {

		QualitySystemExample example = new QualitySystemExample();
		QualitySystemExample.Criteria criteria = example.createCriteria();
		criteria.andStateNotEqualTo(ConstantSqm.STATUS_DELETE);
		criteria.andSupplierIdEqualTo(entity.getSupplierId());
		return	qualitySystemDAO.selectQualitySystemByExample(example);
	
	}

	@Override
	public QualitySystem get(Long id) {
		// TODO Auto-generated method stub
		return qualitySystemDAO.selectQualitySystemByPrimaryKey(id);
	}

	@Override
	public DataGrid<QualitySystem> getDataGrid(QualitySystem entity, Pager pager) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Long insert(QualitySystem entity) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int update(QualitySystem entity) {
		// TODO Auto-generated method stub
		return qualitySystemDAO.updateQualitySystemByPrimaryKey(entity);
	}

	@Override
	public DataGrid<QualitySystemVo> getDataGridVoBy(QualitySystem qualitySystem, Pager pager) {

		return qualitySystemDAO.getDataGridVoBy(qualitySystem, pager);
	}

	@Override
	public void deleteQualitySystem(List<Long> ids) {

		if (ids != null && !ids.isEmpty()) {
			for (int i = 0; i < ids.size(); i++) {
				QualitySystem qualitySystem = qualitySystemDAO.selectQualitySystemByPrimaryKey(ids.get(i));
				qualitySystem.setState(ConstantSqm.STATUS_DELETE);
				qualitySystemDAO.updateQualitySystemByPrimaryKey(qualitySystem);
			}
		}

	}

	@Override
	public QualitySystemVo getModifyData(Long id) throws Exception {
		QualitySystemVo vo=new QualitySystemVo();
		QualitySystem qualitySystem = qualitySystemDAO.selectQualitySystemByPrimaryKey(id);
		BeanUtils.copyProperties(vo, qualitySystem);
		if(qualitySystem.getCertificationDate()!=null)
		vo.setCertificationDates(DateUtil.date2string(qualitySystem.getCertificationDate(), DateUtil.DATE_FORMAT));
		if(qualitySystem.getExpiredDate()!=null)
		vo.setExpiredDates(DateUtil.date2string(qualitySystem.getExpiredDate(), DateUtil.DATE_FORMAT));
		if(qualitySystem.getSelfAssessmentDate()!=null)
		vo.setSelfAssessmentDates(DateUtil.date2string(qualitySystem.getSelfAssessmentDate(), DateUtil.DATE_FORMAT));
		return vo;
	}

	@Override
	public void txUpdateOrAddQualitySystem(String qualitySystem) throws Exception {

		QualitySystemVo vo = new QualitySystemVo();
		Map<String, String> map = null;
		if (StringUtil.isNotBlank(qualitySystem)) {
			map = JsonUtil.json2Bean(qualitySystem, new TypeToken<Map<String, String>>() {
			});
		}
		BeanUtils.populate(vo, map);
		
		QualitySystem bean =qualitySystemDAO.selectQualitySystemByPrimaryKey(vo.getId());
		Supplier supplier = supplierService.get(Long.valueOf(vo.getSupplierId()));

		bean.setComment(vo.getComment());
		bean.setSupplierId(vo.getSupplierId());
		bean.setSupplierCode(supplier.getCode());
		bean.setSupplierName(supplier.getName());
		bean.setValue(vo.getValue());
		bean.setCertificationType(vo.getCertificationType());
		
		if (!StringUtil.isBlank(vo.getUpdateRequired())) {
			bean.setUpdateRequired(vo.getUpdateRequired());
		} else {
			bean.setUpdateRequired(null);
		}
		
		if (!StringUtil.isBlank(vo.getSelfAssessment())) {
			bean.setSelfAssessment(vo.getSelfAssessment());
		} else {
			bean.setSelfAssessment(null);
		}
		
		
		if (!StringUtil.isBlank(vo.getComment())) {
			bean.setComment(vo.getComment());
		} else {
			bean.setComment(null);
		}
		
		if (!StringUtil.isBlank(vo.getContactPerson())) {
			bean.setContactPerson(vo.getContactPerson());
		} else {
			bean.setContactPerson(null);
		} 

		if (!StringUtil.isBlank(vo.getCertificationDates())) {
			bean.setCertificationDate(DateUtil.string2date(vo.getCertificationDates(), DateUtil.DATE_FORMAT));
		} else {
			bean.setCertificationDate(null);
		}
		if (!StringUtil.isBlank(vo.getExpiredDates())) {
			bean.setExpiredDate(DateUtil.string2date(vo.getExpiredDates(), DateUtil.DATE_FORMAT));
		} else {
			bean.setExpiredDate(null);
		}
		
		if (!StringUtil.isBlank(vo.getSelfAssessmentDates())) {
			bean.setSelfAssessmentDate(DateUtil.string2date(vo.getSelfAssessmentDates(), DateUtil.DATE_FORMAT));
		} else {
			bean.setSelfAssessmentDate(null);
		}
		
			qualitySystemDAO.updateQualitySystemByPrimaryKey(bean);
	}

	@Override
	public void txAddQualitySystem(String qualitySystem, ReturnMessage message, BindingResult result) throws Exception {

		QualitySystemVo vo = new QualitySystemVo();
		Map<String, String> map = null;
		if (StringUtil.isNotBlank(qualitySystem)) {
			map = JsonUtil.json2Bean(qualitySystem, new TypeToken<Map<String, String>>() {
			});
		}
		BeanUtils.populate(vo, map);

		QualitySystem bean = new QualitySystem();
		BeanUtils.copyProperties(bean, vo);

		Supplier supplier = supplierService.get(Long.valueOf(vo.getSupplierId()));
		vo.setSupplierCode(supplier.getCode());
		qualitySystemValidator.methodAddValidate(bean, result);
		if (result.hasErrors()) {
			message.setObj(qualitySystemValidator.getErrors(result));
		} else {

			if (!StringUtil.isBlank(vo.getCertificationDates())) {
				bean.setCertificationDate(DateUtil.string2date(vo.getCertificationDates(), DateUtil.DATE_FORMAT));
			}
			if (!StringUtil.isBlank(vo.getExpiredDates())) {
				bean.setExpiredDate(DateUtil.string2date(vo.getExpiredDates(), DateUtil.DATE_FORMAT));
			}
			if(!StringUtil.isBlank(vo.getSelfAssessmentDates())){
				bean.setSelfAssessmentDate(DateUtil.string2date(vo.getSelfAssessmentDates(), DateUtil.DATE_FORMAT));
			}
			
			bean.setSupplierCode(supplier.getCode());
			bean.setSupplierName(supplier.getName());
			bean.setState(ConstantSqm.STATUS_NORMAL);
			
			List<QualitySystem> obj=findListByStateDelete(bean);
			if(obj!=null&&obj.size()>0){
				QualitySystem pojo=obj.get(0);
			 
				pojo.setComment(bean.getComment());
				pojo.setValue(bean.getValue());
				pojo.setUpdateRequired(bean.getUpdateRequired());
				pojo.setCertificationType(bean.getCertificationType());
				pojo.setCertificationDate(bean.getCertificationDate());
				pojo.setExpiredDate(bean.getExpiredDate());
				pojo.setSelfAssessment(bean.getSelfAssessment());
				pojo.setSelfAssessmentDate(bean.getSelfAssessmentDate());
				pojo.setContactPerson(bean.getContactPerson());
				pojo.setState(ConstantSqm.STATUS_NORMAL);
				
				qualitySystemDAO.updateQualitySystemByPrimaryKey(pojo);
			}else{
				qualitySystemDAO.insertQualitySystem(bean);
			}
			message.setSuccess(true);
			message.setMsg(ConstantSqm.OPERATE_SUCCESS);

		}

	
		
	}
	public List<QualitySystem> findListByStateDelete(QualitySystem entity) {
		QualitySystemExample example = new QualitySystemExample();
		QualitySystemExample.Criteria criteria = example.createCriteria();
		criteria.andStateEqualTo(ConstantSqm.STATUS_DELETE);
		criteria.andSupplierIdEqualTo(entity.getSupplierId());
		return qualitySystemDAO.selectQualitySystemByExample(example);
	}
	/**
	 * 查询所有
	 */
	@Override
	public List<QualitySystem> queryAll() {
		QualitySystemExample example = new QualitySystemExample();
		List<QualitySystem> qualitySystemList = qualitySystemDAO.selectQualitySystemByExample(example);
		return qualitySystemList;
	}
	/**
	 * 发送邮件得到用户
	 * @param ids
	 * @return
	 */
	@Override
	public List<User> txgetUserForMail(String ids){
		List<User> userList=new ArrayList<User>();
		if(StringUtil.isEmpty(ids)){
			throw new SystemException("请选择供应商");
		}
		List<QualitySystem> list=quanlitySystemExcelService.getQualitySystemList(ids);
		if(list==null||list.size()<=0){
			throw new SystemException("数据已不存在，请检查");
		}
		for (QualitySystem 	q:list) {
			User user=new User();
			List<Supplier> supplierList=supplierService.findSupplierByCode(q.getSupplierCode());
			if(supplierList!=null&&supplierList.size()>0){
				if(supplierList.get(0).getState().equals(ConstantSqm.STATUS_NORMAL)){
					user.setName(supplierList.get(0).getName());
					user.setMail(supplierList.get(0).getMail());
				}
			}
			if(StringUtil.isEmpty(user.getName())||StringUtil.isEmpty(user.getMail())){
				throw new SystemException("供应商数据不完整，请检查（邮箱、供应商名称）");
			}
			userList.add(user);
		}
		return userList;
	}
	/**
	 * 质量体系发送邮件
	 * @param qualitySystem
	 * @param user
	 * @param request
	 */
	@Override
	public void txSendMail(HttpServletRequest request,HttpServletResponse response,String id){
		//************************四个参数为系统默认邮箱参数，如需修改请到数据字典维护***************************
		// 邮箱服务器名称
		String servicename = dictionaryService.getNameByCodeType(ConstantDict.YXFWQMC, ConstantDict.MAIL);
		// 发送人邮箱名称
		String userEmail = dictionaryService.getNameByCodeType(ConstantDict.FSRYXMC, ConstantDict.MAIL);
		// 邮箱发送密码
		String password = dictionaryService.getNameByCodeType(ConstantDict.FSRYXMM, ConstantDict.MAIL);
		// 邮箱发送人名称
		//String username = dictionaryService.getNameByCodeType(ConstantDict.YXFSRMC, ConstantDict.MAIL);
		String title="质量体系过期提醒";
		quanlitySystemExcelService.txExportPdf(request, id, response);
		//生成pdf
		List<User> userList=txgetUserForMail(id);
		if(userList==null){
			throw new SystemException("用户数据位空，请检查供应商数据");
		}
		if(null==userList.get(0).getMail()||StringUtil.isEmpty(userList.get(0).getMail())){
			throw new SystemException("此供应商无邮箱数据，请检查");
		}
		QualitySystem qualitySystem=get(Long.parseLong(StringUtil.fixup(id)));
		qualitySystem.setMailDate(DateUtil.date2string(new Date()));
		update(qualitySystem);
		String mailbody=userList.get(0).getName()+"</br>您好：</br>贵公司的质量体系认证证书已经过期，详情请见附件";
		SendMail.sendMail(mailbody, servicename, userEmail, password, title, userList.get(0).getMail(), request.getSession().getServletContext()
				.getRealPath("/excelModel/")
				+ "/"+ConstantSqm.PDF_QUALITY_SYSTEM_OUT);
		File deleteFile =new File(request.getSession().getServletContext()
		.getRealPath("/excelModel/")
		+ "/" + ConstantSqm.PDF_QUALITY_SYSTEM_OUT);
		if(deleteFile.exists()){
			deleteFile.delete();
		}
	}
	/**
	 * 向所有过期的供应商发送邮件，不需要参数
	 */
	@Override
	public void txSendMailByDateOut(HttpServletRequest request,HttpServletResponse response){
		int sendCount=0;
		List<QualitySystem> qualitySystemList=queryAll();
		if(qualitySystemList==null){
			throw new SystemException("质量体系数据不存在");
		}
		for (QualitySystem q:qualitySystemList) {
			Date date=new Date();
			if(null!=q.getExpiredDate()&&q.getExpiredDate().before(date)&&q.getState().equals(ConstantSqm.STATUS_NORMAL)){
				if(StringUtil.isEmpty(q.getMailDate())||((q.getMailDate()!=null&&DateUtil.string2date(q.getMailDate()).before(q.getExpiredDate())))){
					txSendMail(request, response, StringUtil.fixup(q.getId()));
					sendCount++;
				}
			}
			
		}
		if(sendCount==0){
			throw new SystemException("没有存在过期的供应商数据");
		}
	}
}
